import os
import sys
import logging


class ProjectInitializer:
    def __init__(self):
        self.root_directory = self.get_project_root()
        self.config = None
        self.add_root_to_env()
        self.initialize_parameters()
        self.setup_logger()

    def initialize_parameters(self):
        """
        初始化参数管理器，加载配置文件并设置默认值。
        """
        from .param_manager import ConfigManager # Corrected to relative import

        config_file = os.path.join(self.root_directory, "config/system.ini")  # 配置文件路径
        config_manager = ConfigManager()
        config_manager.load_config(config_file)
        self.config = config_manager


    def add_root_to_env(self):
        """
        将项目根目录添加到 Python 路径，便于全局模块导入。
        """
        if self.root_directory not in sys.path:
            sys.path.append(self.root_directory)
        # module_dir = os.path.join(self.root_directory, "modules")
        # try:
        #     if os.path.isdir(module_dir) and module_dir not in sys.path:
        #         sys.path.insert(0, module_dir)
        # except Exception:
        #     pass

    def setup_logger(self):
        """
        初始化全局日志器。
        """
        from .logger_manager import LoggerManager # Corrected to relative import

        if self.config.get_param("save_log_to_file"):
            log_file = os.path.join(self.root_directory, "log", "project.log")
        else:
            log_file = None
        log_manager = LoggerManager(name="Rvizx", log_file=log_file, log_level=logging.INFO)
        self.logger = log_manager.get_logger()
        self.logger.info("日志系统已初始化")

    def get_project_root(self):
        """
        获取项目根目录。
        """
        current_dir = os.path.dirname(os.path.abspath(__file__))
        return os.path.abspath(os.path.join(current_dir, "../"))


# # 在模块加载时初始化，并增加添加保护机制
if 'project_initializer' not in globals():
    project_initializer = ProjectInitializer()
    logger = project_initializer.logger
    config = project_initializer.config
    logger.info(project_initializer.root_directory)
